package com.tx.admin.core.repository;

import java.util.List;
import java.util.Optional;

import org.springframework.data.domain.Page;
import org.springframework.data.repository.NoRepositoryBean;

import com.tx.admin.core.entity.TreeEntity;
import com.tx.admin.core.po.PagePo;


@NoRepositoryBean
public interface TreeRepository<E extends TreeEntity<E>> extends SuperRepository<E> {

	
	List<E> findByParentId(String parentId);
	
	
	default Page<E> pageBuildChildren(PagePo<E> params) {
		// TODO Auto-generated method stub
		Page<E> page =  this.page(params);
		page.forEach(val -> {
			List<E> children = this.buildChildren(val);
			val.setChildren(children);
		});
		return page;
	}
	
	default E findByIdBuildParent(String id) {
		Optional<E> op=this.findById(id);
		op.ifPresent(val -> {
			buildParent(val);
		});
		return op.get();
		
	}


	default List<E> buildChildren(E entity) {
		// TODO Auto-generated method stub
		
		List<E> list=this.findByParentId(entity.getId());
		list.parallelStream().forEach(node -> {
			List<E> children=this.buildChildren(node);
			if(children.size()>0) {
				node.setChildren(children);
			}
		});
		return list;
	}



	default E buildParent(E children) {
		// TODO Auto-generated method stub
		Optional<E> op=this.findById(children.getParentId());
		op.ifPresent(parent -> {
			if(parent != null) {
				children.setParent(parent);
				this.buildParent(parent);
			}
		});
		return children;
	}


	
}
